package org.batatasframework.support.definition.impl;

import java.util.ArrayList;
import java.util.Collections;

import org.batatasframework.support.database.metadatas.FieldMetadata;
import org.batatasframework.support.database.sql.TableInstance;
import org.batatasframework.support.database.sql.field.MultipleSelectFragment;
import org.batatasframework.support.database.sql.spi.TableCriterion;
import org.batatasframework.support.definition.FieldDefinitionSourcable;
import org.batatasframework.support.definition.TableDefinition;
import org.batatasframework.support.definition.TableDefinitionResource;

import cn.bonoon.kernel.Flushable;

public abstract class AbstractMultipleFieldDefinition extends AbstractFieldDefinition implements Flushable{

	protected final ArrayList<FieldDefinitionSourcable> fieldSources = new ArrayList<>();
	
//	protected String name;

	protected AbstractMultipleFieldDefinition(String key, TableDefinition searchableContext) {
		super(key, searchableContext);
	}

	@Override
	public boolean contains(FieldMetadata fieldMetadata) {
		if(fieldMetadata == this) return true;
		for(FieldDefinitionSourcable fieldSource : fieldSources){
			if(fieldMetadata == fieldSource.getSourceField()) return true;
		}
		return false;
	}

	protected void _loadFields(TableCriterion tableCriterion, MultipleSelectFragment multipleFragment) throws Exception {
		for(FieldDefinitionSourcable fsd : fieldSources){
			TableInstance tableSource = tableCriterion.safeLoadSource(tableCriterion, fsd.getSourceTable(), true);
			FieldMetadata fieldMetadata = fsd.getSourceField();
			multipleFragment.buildField(tableSource, fieldMetadata);
		}
		
		multipleFragment.setGroup(getGroup());
	}
	
	public void append(FieldDefinitionSourcable...fieldSources){
		Collections.addAll(this.fieldSources, fieldSources);
	}
	
	public void append(String...fieldNames){
		append(tableDefinition, fieldNames);
	}

	public void append(FieldDefinitionSourcable fieldSource){
		this.fieldSources.add(fieldSource);
	}

	public void append(String fieldName){
		append(tableDefinition, fieldName);
	}
	
	public void append(TableDefinitionResource tableDefinition, String fieldName){
		//TableMetadata tableMetadata = tableDefinition.getTableMetadata();
		FieldMetadata sourceField = tableDefinition.get(fieldName);
		fieldSources.add(new DefaultFieldDefinitionResource(tableDefinition, sourceField));
	}
	
	public void append(TableDefinitionResource tableDefinition, String...fieldNames){
		//TableMetadata tableMetadata = tableDefinition.getTableMetadata();
		for(String fieldName : fieldNames){
			FieldMetadata sourceField = tableDefinition.get(fieldName);
			fieldSources.add(new DefaultFieldDefinitionResource(tableDefinition, sourceField));
		}
	}
	
//	@Override
//	public String getName() {
//		return StringHelper.get(name, key);
//	}

	@Override
	public void flush() throws Exception {
		fieldSources.trimToSize();
	}
}
